﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.UI.WebControls;

using CharityGamesOnline.Modules.Common;
using CharityGamesOnline.Modules.Game;

namespace CharityGamesOnline.Modules.Account
{
    public partial class PaymentList : CGOBase
    {
        private int accountUserID;
        private int gameEnrollmentID;

        public int AccountUserID
        {
            get
            {
                if (accountUserID == 0)
                {
                    accountUserID = UserId;
                }
                return accountUserID;
            }
            set
            {
                accountUserID = value;
            }
        }                

        public int GameEnrollmentID
        {
            get
            {
                if (gameEnrollmentID == 0)
                {
                    if (Request.QueryString["GameEnrollmentID"] != null)
                    {
                        gameEnrollmentID = Int32.Parse(Request.QueryString["GameEnrollmentID"]);
                    }
                }
                return gameEnrollmentID;
            }
        }

        public int PayTabID
        {
            get
            {
                if (!Null.IsNull(Settings["PayTabID"]))
                {
                    return Int32.Parse(Settings["PayTabID"].ToString());
                }
                else
                    return TabId;
            }
        }

        public string SharedResources
        {
            get
            {
                return ResolveUrl("App_LocalResources\\SharedResources.resx");
            }
        }

        public bool ShowSectionHead
        {
            get
            {
                if (!Null.IsNull(Settings["ShowSectionHead"]))
                {
                    return Boolean.Parse(Settings["ShowSectionHead"].ToString());
                }
                else
                    return false;
            }
        }

        public bool ShowModuleName
        {
            get
            {
                if (!Null.IsNull(Settings["ShowModuleName"]))
                {
                    return Boolean.Parse(Settings["ShowModuleName"].ToString());
                }
                else
                    return false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                if (!Page.IsPostBack)
                {
                    dshSectionHead.Visible = ShowSectionHead;
                    if (GameEnrollmentID != 0)
                    {
                        lbMessage.Text = string.Format(Localization.GetString("msgPaymentInProcess", SharedResources), GameEnrollmentID);
                    }
                    BindData(true);
                }
            }

            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }

        }                

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            foreach (DataGridColumn column in grdPayment.Columns)
            {
                if (object.ReferenceEquals(column.GetType(), typeof(ImageCommandColumn)))
                {
                    ImageCommandColumn imageColumn = (ImageCommandColumn)column;
                    imageColumn.Visible = false;
                    if (!String.IsNullOrEmpty(imageColumn.CommandName))
                    {
                        imageColumn.Text = Localization.GetString(imageColumn.CommandName, SharedResources);
                    }
                    if (imageColumn.CommandName == "Edit")
                    {
                        string formatString = ModuleContext.EditUrl("PaymentID", "KEYFIELD", "Edit");
                        formatString = formatString.Replace("KEYFIELD", "{0}");
                        imageColumn.NavigateURLFormatString = formatString;
                    }
                }
            }
        }

        protected void grdPayment_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int paymentStatus = Int32.Parse(DataBinder.Eval(e.Item.DataItem, "StatusID").ToString());
                int enrollmentID = Int32.Parse(DataBinder.Eval(e.Item.DataItem,"EnrollmentID").ToString());

                HyperLink lnkPayNow = e.Item.FindControl("lnkPayNow") as HyperLink;
                HyperLink lnkEnroll = e.Item.FindControl("lnkEnroll") as HyperLink;
                LinkButton btnCancel = e.Item.FindControl("btnCancel") as LinkButton;
                Label lbEnrollmentInfo = e.Item.FindControl("lbEnrollmentInfo") as Label;
                
                lnkPayNow.Text = Localization.GetString("lnkPayNow", SharedResources);
                lnkEnroll.Text = Localization.GetString("lnkEnroll", SharedResources);
                    
                if (paymentStatus == (int)PaymentInfo.STATUS.WaitingForPay)
                {
                    lnkPayNow.Visible = true;
                    btnCancel.Visible = true;
                    lnkPayNow.NavigateUrl = Globals.NavigateURL(PayTabID, string.Empty, "PaymentID=" + DataBinder.Eval(e.Item.DataItem, "PaymentID").ToString());
                }
                else if (paymentStatus == (int)PaymentInfo.STATUS.Processing)
                {
                    btnCancel.Visible = false;
                    lnkPayNow.Visible = true;
                    lnkPayNow.Text = Localization.GetString("lnkReTry", SharedResources);
                    lnkPayNow.NavigateUrl = Globals.NavigateURL(PayTabID, string.Empty, "GameEnrollmentID=" + enrollmentID.ToString());
                }
                

                lbEnrollmentInfo.Text = Localization.GetString("NoRelatedEnrollment", SharedResources);
                if (enrollmentID > 0)
                {
                    GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
                    GameEnrollmentInfo objEnroll = ctrlEnroll.GetEnrollment(PortalId, enrollmentID);
                    if (objEnroll != null)
                    {
                        lbEnrollmentInfo.Text = string.Format(Localization.GetString("EnrollmentInfoFormat", SharedResources),
                                                                objEnroll.EventName, objEnroll.GameName);
                        if (!Null.IsNull(Settings["EventDetailTabID"]))
                        {
                            lnkEnroll.Visible = true;
                            lnkEnroll.NavigateUrl = Globals.NavigateURL(Int32.Parse(Settings["EventDetailTabID"].ToString()),
                                                                    string.Empty, "EventID=" + objEnroll.EventID);
                        }
                    }
                }
            }
        }

        protected void grdPayment_ItemCreated(object sender, DataGridItemEventArgs e)
        {
            LinkButton btnCancel = e.Item.FindControl("btnCancel") as LinkButton;
            if (btnCancel != null)
            {
                btnCancel.Text = Localization.GetString("btnCancel", SharedResources);
                btnCancel.Click += new EventHandler(btnCancel_Click);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            LinkButton btnCancel = sender as LinkButton;
            PaymentController ctrlPayment = new PaymentController();
            PaymentInfo objPayment = ctrlPayment.GetPayment(PortalId, Int32.Parse(btnCancel.CommandArgument));
            if (objPayment != null)
            {
                objPayment.StatusID = (int)PaymentInfo.STATUS.Cancel;
                ctrlPayment.SavePayment(objPayment);                
                BindData(false);
            }
        }

        protected void cgoPaging_PageChangeEvent(object sender, EventArgs e)
        {
            BindData(false);            
        }

        private void BindData(bool refreshPaging)
        {
            PaymentController ctrlPayment = new PaymentController();
            List<PaymentInfo> lstPayment;
            cgoPaging.Visible = true;
            lstPayment = ctrlPayment.GetPayments(PortalId, AccountUserID, 0, refreshPaging, cgoPaging.PageSize, cgoPaging.CurrentPage);
            if (refreshPaging && lstPayment.Count > 0 && lstPayment[0].TotalRowCount > cgoPaging.PageSize)
            {                
                cgoPaging.TotalCount = lstPayment[0].TotalRowCount;
            }

            if (cgoPaging.TotalCount < cgoPaging.PageSize)
            {
                cgoPaging.Visible = false;
            }
            grdPayment.DataSource = lstPayment;
            grdPayment.DataBind();
        }
    }
}